package com.todod.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.todod.common.util.BeanUtilEx;
import com.todod.common.util.SnowflakeIdGenerator;
import com.todod.exception.CustomException;
import com.todod.mapper.MenuMapper;
import com.todod.model.Menu;
import com.todod.service.IAuthorityService;
import com.todod.service.IMenuService;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author gsh
 * @since 2020-11-16
 */
@Service
@Transactional
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {

	@Autowired
	private IAuthorityService iAuthorityService;

	@Override
	public void saveData(Long _userId, Menu menu) {
		if (menu.getParentId() == null) {
			menu.setParentId(0l);
		}
		if (menu.getId() == null) {
			menu.setId(SnowflakeIdGenerator.getId());
			menu.setCreateTime(LocalDateTime.now());
			menu.setCreateUserId(_userId);

			this.save(menu);
		} else {
			Menu u = getById(menu.getId());

			try {
				BeanUtilEx.copyProperties(u, menu);
			} catch (Exception e) {
				log.error("error", e);
			}

			u.setModifyUserId(_userId);
			u.setModifyTime(LocalDateTime.now());

			this.updateById(u);
		}

	}

	@Override
	public void delete(Long _userId, Long id) {
		List<Menu> list = getByParentId(id);

		if (list != null && list.size() != 0) {
			throw new CustomException("有下级节点，不能删除");
		}

		removeById(id);

		iAuthorityService.deleteByMenuId(_userId, id);
	}

	@Override
	public List<Menu> getByParentId(Long parentId) {

		QueryWrapper<Menu> wrapper = new QueryWrapper<Menu>();
		wrapper.eq("sm_parent_id", parentId);
		return list(wrapper);
	}

	@Override
	public List<Menu> getList() {
		QueryWrapper<Menu> wrapper = new QueryWrapper<Menu>();
		wrapper.orderByAsc("sm_sort_num");
		List<Menu> list = list(wrapper);

		return list;
	}

}
